package com.banshou.installs.ui.activity;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.ArrayMap;
import android.view.View;

import com.banshou.installs.R;
import com.banshou.installs.constant.BaseApplication;
import com.banshou.installs.constant.Config;
import com.banshou.installs.databinding.ForgrtPassBinding;
import com.banshou.installs.model.dao.RequestFirstLoginUpdatePass;
import com.banshou.installs.model.dao.RequestForgetPass;
import com.banshou.installs.model.dao.ResponseCheckCode;
import com.banshou.installs.model.dao.ResponseLogin;
import com.banshou.installs.model.net.Observer;
import com.banshou.installs.model.net.ResponseInfo;
import com.banshou.installs.model.net.RetrofitManager;
import com.banshou.installs.model.net.RetrofitManager2;
import com.banshou.installs.model.net.RxUtil;
import com.banshou.installs.utils.DialogUtils;
import com.banshou.installs.utils.SharePreUtil;
import com.banshou.installs.utils.ToastUtil;
import com.blankj.utilcode.util.RegexUtils;
import com.orhanobut.logger.Logger;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by cjq on 2017/12/28.
 * Email: stoic_yb@139.com
 * features: 忘记密码
 */

public class ForgetPassActivity extends BaseActivity implements View.OnClickListener {
    private ForgrtPassBinding mBinding;
    private Map<String, String> map;
    private String type;
    private DialogUtils dialogUtils;
    private int numcode = 345241;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.forgrt_pass);
        initView();
    }

    private void initView() {
        map = new ArrayMap<>();
        dialogUtils = new DialogUtils();
        type = getIntent().getStringExtra(Config.FROMTOPASS);
        if (type != null && type.equals(Config.LOGIN_FORGET_PASS)) {
            mBinding.title.pagerTitle.setText(R.string.login_forget);
        } else {
            mBinding.forTel.setText(SharePreUtil.getTel(BaseApplication.getContext(), "NULL"));
            mBinding.title.pagerTitle.setText(R.string.set_pass);
        }
        mBinding.title.pagerTitle.setOnClickListener(this);
        mBinding.next.setOnClickListener(this);
        mBinding.title.back.setOnClickListener(this);
        mBinding.forGetcheck.setOnClickListener(this);
        mBinding.forIncheck.addTextChangedListener(checkWacher);
        mBinding.forPass.addTextChangedListener(passWacher);
        setButton();
    }

    private void setButton() {
        mBinding.forTel.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence s, int i, int i1, int count) {
                int length = s.toString().length();
                if (length == 13 && !TextUtils.isEmpty(mBinding.forIncheck.getText().toString()) && !TextUtils.isEmpty(mBinding.forPass.getText().toString())) {
                    mBinding.next.setEnabled(true);
                } else {
                    mBinding.next.setEnabled(false);
                }
                //删除数字
                if (count == 0) {
                    if (length == 4) {
                        mBinding.forTel.setText(s.subSequence(0, 3));
                    }
                    if (length == 9) {
                        mBinding.forTel.setText(s.subSequence(0, 8));
                    }
                }
                //添加数字
                if (count == 1) {
                    if (length == 4) {
                        String part1 = s.subSequence(0, 3).toString();
                        String part2 = s.subSequence(3, length).toString();
                        mBinding.forTel.setText(part1.concat(" ").concat(part2));
                    }
                    if (length == 9) {
                        String part1 = s.subSequence(0, 8).toString();
                        String part2 = s.subSequence(8, length).toString();
                        mBinding.forTel.setText(part1.concat(" ").concat(part2));
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
                mBinding.forTel.setSelection(mBinding.forTel.getText().toString().length());
            }
        });
    }

    public TextWatcher checkWacher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (TextUtils.isEmpty(mBinding.forTel.getText().toString()) || TextUtils.isEmpty(mBinding.forIncheck.getText().toString()) || TextUtils.isEmpty(mBinding.forPass.getText().toString())) {
                mBinding.next.setEnabled(false);
            } else {
                mBinding.next.setEnabled(true);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    };
    public TextWatcher passWacher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (TextUtils.isEmpty(mBinding.forTel.getText().toString()) || TextUtils.isEmpty(mBinding.forIncheck.getText().toString()) || TextUtils.isEmpty(mBinding.forPass.getText().toString())) {
                mBinding.next.setEnabled(false);
            } else {
                mBinding.next.setEnabled(true);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.for_getcheck:
                if (!RegexUtils.isMobileSimple(mBinding.forTel.getText().toString().trim().replace(" ",""))) {
                    ToastUtil.toast(Config.RIGHTTEL);
                    return;
                }
                final MyCountDownTimer myCountDownTimer = new MyCountDownTimer(60000, 1000);
                myCountDownTimer.start();
                numcode = (int) ((Math.random() * 9 + 1) * 100000);
                com.orhanobut.logger.Logger.d(numcode);
                String code = encode("bswl001");
                String name = "您的验证码为：" + numcode + "【装屏助手】";
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(Config.CHECKCODEURL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
                retrofit.create(ResponseInfo.class)
                        .getCheckCode("sd", "bswlhy", code, mBinding.forTel.getText().toString().trim().replace(" ",""), name, "", "send", "")
                        .enqueue(new Callback<ResponseCheckCode>() {
                            @Override
                            public void onResponse(Call<ResponseCheckCode> call, Response<ResponseCheckCode> response) {
                            }

                            @Override
                            public void onFailure(Call<ResponseCheckCode> call, Throwable t) {
                                com.orhanobut.logger.Logger.d(t.toString());
                                ToastUtil.toast(Config.NONET);
                            }
                        });
                break;
            case R.id.next:
                String tel = mBinding.forTel.getText().toString().trim().replace(" ","");
                String pass = mBinding.forPass.getText().toString().trim();
                if (!RegexUtils.isMobileSimple(tel)) {
                    ToastUtil.toast(Config.RIGHTTEL);
                    return;
                }
                if (!mBinding.forIncheck.getText().toString().trim().equals(String.valueOf(numcode))) {
                    ToastUtil.toast("验证码错误");
                    return;
                }
                map.clear();
                if (type != null && type.equals(Config.LOGIN_FIRST_PASS)) {
                    RequestFirstLoginUpdatePass updatePass = new RequestFirstLoginUpdatePass(pass);
                    firstLoginUpdatePassword(updatePass);
                } else {
                    RequestForgetPass forgetPass = new RequestForgetPass(tel, pass);
                    forgetPassword(forgetPass);
                }
                break;
        }
    }

    /**
     * 忘记密码/修改密码
     */
    private void forgetPassword(RequestForgetPass forgetPass) {
        dialogUtils.showAni(this);
        RetrofitManager2.getInstance()
                .create(ResponseInfo.class)
                .forgetPwd(forgetPass)
                .compose(RxUtil.lifecycle(this))
                .subscribe(new Observer<ResponseLogin>() {
                    @Override
                    protected void onNextStep(ResponseLogin login) {
                        dialogUtils.hideAni();
                        if (type.equals(Config.SET_UPDATE_PASS)) {
                            ToastUtil.toast(Config.UPDATE);
                            finish();
                        } else {
                            ToastUtil.toast("密码修改成功，请重新登录");
                            Intent intent = new Intent(ForgetPassActivity.this, LoginActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    }

                    @Override
                    protected void onErrorResult() {
                        dialogUtils.hideAni();
                    }
                });
    }

    /**
     * 员工第一次登录修改密码
     */
    private void firstLoginUpdatePassword(RequestFirstLoginUpdatePass updatePass) {
        dialogUtils.showAni(this);
        RetrofitManager2.getInstance()
                .create(ResponseInfo.class)
                .updateFirstPwd(updatePass)
                .compose(RxUtil.lifecycle(this))
                .subscribe(new Observer<ResponseLogin>() {
                    @Override
                    protected void onNextStep(ResponseLogin responseLogin) {
                        dialogUtils.hideAni();
                        Intent intent = new Intent(ForgetPassActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    protected void onErrorResult() {
                        dialogUtils.hideAni();
                    }
                });
    }


    //    md5 32位大写加密
    public static String encode(String text) {
        try {
            MessageDigest digest = MessageDigest.getInstance("md5");
            byte[] result = digest.digest(text.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : result) {
                int number = b & 0xff;
                String hex = Integer.toHexString(number);
                if (hex.length() == 1) {
                    sb.append("0" + hex);
                } else {
                    sb.append(hex);
                }
            }
            return sb.toString().toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return "";
    }

    private class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        //计时过程
        @Override
        public void onTick(long l) {
            //防止计时过程中重复点击
            mBinding.forGetcheck.setClickable(false);
            mBinding.forGetcheck.setBackgroundColor(Color.GRAY);
            mBinding.forGetcheck.setText("重新获取" + l / 1000 + "s");

        }

        //计时完毕的方法
        @Override
        public void onFinish() {
            //重新给Button设置文字
            mBinding.forGetcheck.setText("重新获取验证码");
            mBinding.forGetcheck.setBackgroundColor(getResources().getColor(R.color.color_gray));
            //设置可点击
            mBinding.forGetcheck.setClickable(true);
        }
    }
}
